package com.xjk.xml;

import java.io.ByteArrayOutputStream;

import javax.xml.bind.Marshaller;

/**
 * 用来解决xml文件中自定义头的问题
 */
public class MarshallerUtilExt extends MarshallerUtil{
    
    public static String buildJaxbSafe(Object object, Boolean format) throws RuntimeException {
        String result = null;
        Marshaller marshaller = null;
        try {
            Class<?> clazz = object.getClass();
            marshaller = (Marshaller) marPool.borrowObject(clazz);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, format);
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            // 加上自定义的头信息
            os.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>".getBytes());
            marshaller.marshal(object, os);
            result = new String(os.toByteArray(), "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException("XML转换失败", e);
        } finally {
            // 归还到对象池
            if (object != null) {
                try {
                    marPool.returnObject(object.getClass(), marshaller);
                } catch (Exception e) {

                }
            }
        }
        return result;
    }
}